var util = require('../../libs/util.js');
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
var app = getApp();
var mapCtx;
var loactionSetInterval;
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    middle_height: "100vh",
    delivery_date: util.dateObjectformat(new Date(), 'yyyy-MM-dd'),
    delivery_date_text: "今天配送",
    delivery_data: [],
    delivery_data_filter: [],
    tpData:[],
    detailShow: '',
    dd_style: "",
    path_data: [],
    warehouse: '全部项目',
    warehouseId: '',
    is_schedule: false,
    shareMode: 0,
    statusType: 'all',
    tab: 1,
    mode: 'delivery',
    stats: {
      shopNumber: 0,
      nostart: 0,
      undertaking: 0,
      receiving_order: 0,
      delivery: 0,
      delivery_end: 0,
      end: 0
    },
    coAdmin: app.globalData.coAdmin,
    mapMode: 'vehicle', //vehicle,vehicle_trace
    latitude: 0, //纬度 
    longitude: 0, //经度 
    markers: [],
    polyline: [],
    "include-points": []
  },
  onPullDownRefresh: function () {
    //wx.stopPullDownRefresh()
  },
  onReady: function (e) {
    mapCtx = wx.createMapContext('map');
  },
  onShow: function (e) {
    var that = this;
    wx.getStorage({
      key: 'monitor_warehouse',
      success: function (res) {
        if (res.data) {
          that.setData({
            warehouse: String(res.data.abbreviation || res.data.name).substr(0, 10),
            warehouseId: res.data.value
          });
          that.loadData();
        }
      },
      complete: function (res) {
        wx.removeStorage({
          key: 'monitor_warehouse',
          success: function (res) {}
        });
      }
    });
  },
  //切换模式
  changeMode: function (e) {
    var that = this;
    this.setData({
      mode: e.currentTarget.dataset.mode
    })
    loactionSetInterval = null;
    if (e.currentTarget.dataset.mode == 'delivery') {
      this.loadData();
      loactionSetInterval = setInterval(function () {
        that.loadData();
      }, 120000);
    }
    if (e.currentTarget.dataset.mode == 'location') {
      if (that.data.mapMode == 'vehicle') {
        this.loadMapData();
        loactionSetInterval = setInterval(function () {
          that.loadMapData();
        }, 120000);
      } else {
        this.loadMapTraceData();
        loactionSetInterval = setInterval(function () {
          that.loadMapTraceData();
        }, 120000);
      }
    }
    if (e.currentTarget.dataset.mode == 'tp') {
      this.loadTpData();
        loactionSetInterval = setInterval(function () {
          that.loadTpData();
        }, 120000);
    }
  },
  //筛选
  changeStatusType: function (e) {
    var that = this;
    var statusType = e.currentTarget.dataset.type;
    this.setData({
      statusType: statusType
    });
    wx.createSelectorQuery().select('.delivery-list-item').node(function (res) {
      console.log(res)
      if (res == null) {
        that.setData({
          nodata: true
        })
      } else {
        that.setData({
          nodata: false
        })
      }
    }).exec()
  },
  getLocation(callback) {
    var that = this;
    //获取手机定位坐标
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res.latitude)
        var latitude = res.latitude;
        var longitude = res.longitude;
        that.setData({
          longitude: longitude,
          latitude: latitude
        });
        if (callback) {
          callback(longitude, latitude)
        }
      }
    });
  },
  onLoad: function (e) {
    var that = this;
    wx.setNavigationBarTitle({
      "title": app.appName + "--配送监控"
    });

    try {
      if (app.globalData.role_default == 'schedule' || app.globalData.role_default == 'admin' || app.globalData.role_default == 'operation') {
        that.setData({
          is_schedule: true
        })
      }
    } catch (e) {}
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        that.setData({
          middle_height: res.windowHeight - (that.data.is_schedule ? 52 : 0) - 40 - 60.8 - app.globalData.CustomBar,
          detail_height: res.windowHeight - 40
        });
      }
    });
    if (e.warehouseid) {
      that.setData({
        warehouse: e.warehouse,
        warehouseId: e.warehouseid
      });
    }
    if (e.shareMode) {
      that.setData({
        shareMode: 1
      })
    }
    that.getLocation();
    that.loadData();
  },
  switchChange(e) {
    console.log(e)
    var that = this;
    var item = String(e.currentTarget.id),
      item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  onShareAppMessage: function () {
    return {
      title: app.appName + '-配送监控',
      path: '/pages/schedule/monitor?shareMode=1&co_id=' + app.globalData.CO_ID + '&warehouse=' + this.data.warehouse + '&warehouseid=' + this.data.warehouseId
    }
  },
  loadData: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    util.getData("/atapi/delivery/process/getDeliveryMonitor", {
      CO_ID: app.globalData.CO_ID,
      delivery_date: that.data.delivery_date,
      warehouseId: that.data.warehouseId,
      shareMode: that.data.shareMode
    }, function (res, error) {
      console.log(res);
      console.log(error)
      setTimeout(function () {
        wx.hideLoading();
      }, 100);
      if (res.data.success) {
        console.log(res.data)
        var delivery_data = res.data.data;
        if (that.data.delivery_data.length > 0) {
          var deliveryData = that.data.delivery_data;
          for (var i = 0; i < delivery_data.length; i++) {
            for (var j = 0; j < deliveryData.length; j++) {
              if (delivery_data[i].ID == deliveryData[j].ID) {
                if (deliveryData[j].tp) delivery_data[i].tp = deliveryData[j].tp;
                if (deliveryData[j].latitude) delivery_data[i].latitude = deliveryData[j].latitude;
                if (deliveryData[j].longitude) delivery_data[i].longitude = deliveryData[j].longitude;
                if (deliveryData[j].address) delivery_data[i].address = deliveryData[j].address;
                if (deliveryData[j].nextDistance) delivery_data[i].nextDistance = deliveryData[j].nextDistance;
                if (deliveryData[j].nextDurtion) delivery_data[i].nextDurtion = deliveryData[j].nextDurtion;
              }
            }
          }
        }
        that.setData({
          delivery_data: delivery_data,
          stats: res.data.stats
        });
        //socket
        // app.socket.on('alliot', function (data) {
        //   //console.log(data)
        //   var delivery_data = that.data.delivery_data;
        //   var tp_exception = 0;
        //   for (var i = 0; i < delivery_data.length; i++) {
        //     if(delivery_data[i].driver_status != 'end'){
        //       if ((data.iotbox == delivery_data[i].iot_box  && delivery_data[i].iot_box != null) || data.iotbox == 'WX' + delivery_data[i].user_id) {
        //         if (data.temperature) {
        //           delivery_data[i].temperature = data.temperature;
        //           delivery_data[i].tp_time = data.time;
        //           if ((data.temperature > 10 || data.temperature < -18) && delivery_data[i].driver_status != 0 && delivery_data[i].driver_status != 'delivery_end' && delivery_data[i].driver_status != 'end') {
        //             delivery_data[i].tp_exception = 1;
        //           } else {
        //             delivery_data[i].tp_exception = 0;
        //           }
        //         }
        //         if (data.latitude) {
        //           delivery_data[i].latitude = data.latitude;
        //           delivery_data[i].longitude = data.longitude;
        //           delivery_data[i].gps_time = data.time;
        //         }
        //         that.setData({
        //           delivery_data: delivery_data
        //         });
        //       }
        //       if (delivery_data[i].tp_exception == 1) {
        //         tp_exception++;
        //       }
        //     }
            
        //   }
        //   that.setData({
        //     'stats.tp_exception': tp_exception
        //   });
        // });
        //定时更新位置
        setInterval(function () {
          that.updateVehicleLocation();
        }, 60000);
      } else {
        that.setData({
          hasData: false,
          delivery_data: [],
          stats: {
            shopNumber: 0,
            nostart: 0,
            undertaking: 0,
            receiving_order: 0,
            delivery: 0,
            delivery_end: 0,
            end: 0,
            completion_rate: 0,
            time_exception: 0,
            delay: 0,
            tp_exception: 0
          }
        })
      }
    });

  },
  loadTpData:function(){
      var that = this;
      var delivery_data = that.data.delivery_data;
      var tpData = that.data.tpData;
      if(tpData.length == 0){
        var deliveryIdList = [];
        for(var i=0;i<delivery_data.length;i++){
          deliveryIdList.push(delivery_data[i].ID);
        }
        util.getData("/atapi/delivery/process/getDeliveryTpTrace", {
          delivery: deliveryIdList.join(',')
        }, function (res) {
          console.log(res)
          if (res.data.success) {
              that.setData({
                tpData:res.data.data
              })
          }
        });
      }
  },
  loadMapData: function () {
    var that = this;
    var delivery_data = that.data.delivery_data;
    that.setData({
      polyline: []
    });
    var markers = [],
      lalt = [];
    var icon = '/images/truck.png',
      width = 24,
      height = 24;;
    for (var i = 0; i < delivery_data.length; i++) {
      if (delivery_data[i].latitude) {
        markers.push({
          id: delivery_data[i].ID,
          title: delivery_data[i].plate,
          callout: {
            content: delivery_data[i].plate + (delivery_data[i].temperature ? '，温度：' + delivery_data[i].temperature + '°C' : ''),
            fontSize: 11,
            color: '#ffffff',
            borderRadius: 3,
            bgColor: '#000000',
            padding: 3,
            display: 'ALWAYS'
          },
          iconPath: icon,
          width: width,
          height: height,
          longitude: delivery_data[i].longitude,
          latitude: delivery_data[i].latitude
        });
        lalt.push({
          longitude: delivery_data[i].longitude,
          latitude: delivery_data[i].latitude
        })
      }
    }
    if (markers.length > 0) {
      that.setData({
        markers: markers
      });
      mapCtx.includePoints({
        padding: [10],
        points: lalt
      })
    }
  },
  backToVehicleMap: function () {
    this.setData({
      mapMode: 'vehicle'
    })
    loactionSetInterval = null;
    this.loadMapData();
    loactionSetInterval = setInterval(function () {
      that.loadMapData();
    }, 60000);
  },
  markertap: function (e) {
    var that = this;
    if (isNaN(e.markerId) == true) {
      return false;
    }
    console.log(e)
    var plate = '';
    var delivery_data = that.data.delivery_data;
    for (var i = 0; i < delivery_data.length; i++) {
      if (delivery_data[i].ID == e.markerId) {
        plate = delivery_data[i].plate;
      }
    }
    that.setData({
      mapMode: 'vehicle_trace',
      currentMarkerId: e.markerId,
      currentPlate: plate
    })
    loactionSetInterval = null;
    this.loadMapTraceData();
    loactionSetInterval = setInterval(function () {
      that.loadMapTraceData();
    }, 60000);
  },
  loadMapTraceData() {
    var that = this;
    util.getData("/atapi/delivery/process/getDeliveryMonitorTrace", {
      delivery: that.data.currentMarkerId
    }, function (res) {
      console.log(res)
      var lalt = [];
      var markers = [];
      if (res.data.success) {
        var traceData = res.data.data[0],
          pointData = res.data.data[1];
        for (var i = 0; i < traceData.length; i++) {
          lalt.push({
            longitude: traceData[i].longitude,
            latitude: traceData[i].latitude
          });
          markers.push({
            id: 'T' + traceData[i].ID,
            title: traceData[i].plate,
            callout: {
              content: moment(traceData[i].gps_time).format('HH时mm分') + (traceData[i].temperature ? '\n温度：' + traceData[i].temperature + '°C' : ''),
              fontSize: 11,
              color: '#ffffff',
              borderRadius: 3,
              bgColor: '#000000',
              padding: 3,
              display: 'ALWAYS'
            },
            iconPath: '/images/space.png',
            width: 0,
            height: 0,
            longitude: traceData[i].longitude,
            latitude: traceData[i].latitude
          })
        }
        for (var i = 0; i < pointData.length; i++) {
          var coord = String(pointData[i].wh_coord || pointData[i].s_coord).split(",");
          markers.push({
            id: 'P' + pointData[i].ID,
            callout: {
              content: (pointData[i].wh_name || pointData[i].s_name),
              fontSize: 11,
              color: '#ffffff',
              borderRadius: 3,
              bgColor: '#1C64E8',
              padding: 3,
              display: 'ALWAYS'
            },
            iconPath: '/images/space.png',
            width: 0,
            height: 0,
            longitude: coord[1],
            latitude: coord[0]
          })
        }
        var polyline = [{
          points: lalt,
          color: "#1C64E8",
          width: 2,
          arrowLine: true
        }]
      }
      that.setData({
        polyline: polyline,
        markers: markers
      })
      mapCtx.includePoints({
        padding: [10],
        points: lalt
      })
    });
  },
  updateVehicleLocation: function () {
    var that = this;
    var delivery_data = that.data.delivery_data;
    for (var i = 0; i < delivery_data.length; i++) {
      if (delivery_data[i].latitude) {
        util.getData("/xypapi/map/routerCalculate/getVehicleLocationOfDelivery", {
          ID: delivery_data[i].ID,
          longitude: delivery_data[i].longitude,
          latitude: delivery_data[i].latitude
        }, function (res) {
          //console.log(res)
          if (res.data.success) {
            var address = res.data.address;
            try {
              if (res.data.data.distance) {
                var duration = res.data.data.duration / 60;
                var _hour = Math.floor(duration / 60);
                var _minute = Number(duration - _hour * 60).toFixed(0);
                var nextDistance = Number(res.data.data.distance / 1000).toFixed(1);
                var nextDurtion = _hour + '时' + _minute + '分';
              }
            } catch (e) {};
            var deliveryData = that.data.delivery_data;
            for (var i = 0; i < deliveryData.length; i++) {
              if (deliveryData[i].ID == res.data.ID) {
                deliveryData[i].address = address;
                if (nextDistance) {
                  deliveryData[i].nextDistance = nextDistance;
                  deliveryData[i].nextDurtion = nextDurtion;
                }
                that.setData({
                  delivery_data: deliveryData
                })
              }
            }
          }
        });
      }
    }
  },
  changeDeliveryDate: function (e) {
    this.setData({
      delivery_date: e.detail.value,
      delivery_date_text: e.detail.value
    });
    this.loadData();
  },
  changeWarehouse: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/schedule/monitor_warehouse'
    })
  },
  showDeliveryDetail: function (e) {
    var that = this;
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/order/order?id=' + id
    })
  }
})